﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Senbo.Areas.Admin.Models.ViewDatas;
using Senbo.Model.Entities;
using Senbo.Model;

namespace Senbo.Areas.Admin.Controllers
{
    public class CategoryController : BaseAdminController
    {
        public ActionResult Index()
        {
            List<Category> categoryList = new List<Category>();
            using (SenboDBContext db = new SenboDBContext())
            {
                categoryList = db.Categorys.ToList();
            }
            Category_IndexViewData vd = new Category_IndexViewData()
            {
                CategoryList = categoryList
            };
            return View(vd);
        }

        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            bool isEdit = id > 0;
            Category category = null;
            if (isEdit)
            {
                using (SenboDBContext db = new SenboDBContext())
                {
                    category = db.Categorys.FirstOrDefault(z => z.Id == id);
                }
            }
            else
            {
                category = new Category();
            }
            Category_EditViewData vd = new Category_EditViewData()
            {
                IsEdit = isEdit,
                Category = category
            };
            return View(vd);
        }

        [HttpPost]
        public ActionResult Edit([Bind(Prefix = "Category")]Category category_Form)
        {
            bool isEdit = category_Form.Id > 0;
            if (!ModelState.IsValid)
            {
                Category_EditViewData vd = new Category_EditViewData()
                {
                    IsEdit = isEdit,
                    Category = category_Form
                };
                return View(vd);
            }
            Category category = null;
            if (isEdit)
            {
                //using (SenboDBContext db = new SenboDBContext())
                //{
                //    UpdateModel(
                //}
            }
            else
            {
                using (SenboDBContext db = new SenboDBContext())
                {
                    category = new Category()
                    {
                        Name = category_Form.Name,
                        AddTime = DateTime.Now
                    };
                    db.Categorys.Add(category);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("Index");
        }

    }
}
